<template>
  <div class="login">
    <el-card class="container">
      <!-- 账号密码登录 -->
      <el-form
        v-if="chooseLoginType == 'username'"
        ref="loginUsernameForm"
        :model="loginUsernameParams"
        label-width="100px"
        :rules="usernameRules"
      >
        <!-- 账号输入框 -->
        <el-form-item
          label="账号"
          prop="username"
        >
          <el-input
            v-model="loginUsernameParams.username"
            type="input"
            style="width:200px"
          ></el-input>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="loginUsernameParams.password"
            type="password"
            style="width:200px"
          ></el-input>
        </el-form-item>
        <!-- 验证码输入框 -->
        <el-form-item
          label="验证码"
          prop="captcha"
        >
          <el-input
            v-model="loginUsernameParams.captcha"
            type="input"
            style="width:100px"
          ></el-input>
          <div
            class="check_pic"
            @click="getCaptcha()"
            v-html="captchaImg"
          ></div>
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <div class="btns">
            <el-button
              size="small"
              type="primary"
              @click="submitForm()"
            >
              登录
            </el-button>
            <el-button 
              size="small"
              @click="resetForm()"
            >
              清空
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <!-- 邮箱验证登录 -->
      <el-form
        v-if="chooseLoginType == 'email'"
        ref="loginEmailForm"
        :model="loginEmailParams"
        label-width="100px"
        :rules="emailRules"
      >
        <!-- 邮箱账号输入框 -->
        <el-form-item
          label="邮箱账号"
          prop="email"
        >
          <el-input
            v-model="loginEmailParams.email"
            type="input"
            style="width:200px"
          ></el-input>
        </el-form-item>
        <!-- 邮箱验证码输入框 -->
        <el-form-item
          label="验证码"
          prop="emailCode"
        >
          <el-input
            v-model="loginEmailParams.emailCode"
            type="input"
            style="width:90px"
          ></el-input>
          <el-link
            style="width:110px;color: #337ecc;"
            @click="reduceSendEmail()"
          >
            {{ interval == 0 ? '发送邮箱验证' : `已发送(${interval})` }}
          </el-link>
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <div class="btns">
            <el-button
              size="small"
              type="primary"
              @click="submitForm()"
            >
              登录
            </el-button>
            <el-button 
              size="small"
              @click="resetForm()"
            >
              清空
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <el-link
        class="login_type"
        @click="chooseLoginType == 'username' ? chooseLoginType = 'email' : chooseLoginType = 'username'"
      >
        {{ chooseLoginType == 'username' ? '邮箱验证登录' : '账号密码登录' }}
      </el-link>
      <el-link
        class="register_link"
        @click="toRegister()"
      >
        没有账号？立即注册
      </el-link>
    </el-card>
  </div>
</template>

<script lang='ts' setup name="login">
import api from './service/api'
import func from '@/utils/tools'
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import Md5 from 'md5'
import axios from 'axios'

const router = useRouter()
const chooseLoginType = ref('username')
const captchaImg = ref(null)
// 收集的登录信息
const loginUsernameParams = reactive({
    username: '',
    password: '',
    captcha: '',
})
const loginEmailParams = reactive({
    email: '',
    emailCode: '',
})

const loginUsernameForm = ref<FormInstance>()
const loginEmailForm = ref<FormInstance>()

const submitForm = () => {
    if (loginUsernameForm.value && chooseLoginType.value == 'username') {
        let commitParams = {
            username: loginUsernameParams.username,
            password: loginUsernameParams.password,
            captcha: loginUsernameParams.captcha,
        }
        loginUsernameForm.value.validate((valid) => {
            if (valid) {
                commitParams.password = Md5(loginUsernameParams.password)
                api.pwdLogin(commitParams).then(res => {
                    const { code, data, msg } = res
                    if (code === 0) {
                        func.setCookie('ev-token', data.token, 1)
                        ElMessage({
                            message: msg,
                            type: 'success',
                        })
                        router.push('/business/chartList')
                    } else {
                        ElMessage({
                            message: msg,
                            type: 'error',
                        })
                    }
                })
                getCaptcha()
            } else {
                ElMessage({
                    message: '信息填写不完整',
                    type: 'warning',
                })
                return false
            }
        })
    } else if (loginEmailForm.value && chooseLoginType.value == 'email') {
        let commitParams = {
            email: loginEmailParams.email,
            emailCode: loginEmailParams.emailCode,
        }
        loginEmailForm.value.validate((valid) => {
            if (valid) {
                api.emailLogin(commitParams).then(res => {
                    const { code, data, msg } = res
                    if (code === 0) {
                        func.setCookie('ev-token', data.token, 1)
                        ElMessage({
                            message: msg,
                            type: 'success',
                        })
                        router.push('/business/chartList')
                    } else {
                        ElMessage({
                            message: msg,
                            type: 'error',
                        })
                    }
                })
            } else {
                ElMessage({
                    message: '信息填写不完整',
                    type: 'warning',
                })
                return false
            }
        })
    }
}
const usernameRules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
    ],
})
const emailRules = reactive<FormRules>({
    email: [
        { required: true, message: '请输入邮箱号', trigger: 'blur' },
    ],
    emailCode: [
        { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    ],
})

// 清空表单数据
const resetForm = () => {
    if (loginUsernameForm.value) {
        loginUsernameForm.value.resetFields()
    }
    if (loginEmailForm.value) {
        loginEmailForm.value.resetFields()
    }
}

const interval = ref(0)
const timer = ref(0)
// 发送邮箱验证码
const reduceSendEmail = () => {
    if (interval.value == 0) {
        sendEmail()
        interval.value = 60
        emailTimeOut()
    } else {
        ElMessage({
            message: '每60s只能发送一次邮件',
            type: 'warning',
        })
    }
}
const emailTimeOut = () => {
    timer.value = window.setInterval(() => { 
        if (interval.value > 0) {
            interval.value--
        } else {
            clearInterval(timer.value)
        }
    }, 1000)
}
const sendEmail = () => {
    let data = { email: loginEmailParams.email }
    api.sendEmail(data).then(res => {
        const { code, data, msg } = res
        if (code == 0) {
            ElMessage({
                message: msg,
                type: 'success',
            })
        } else {
            ElMessage({
                message: msg,
                type: 'error',
            })
        }
    })
}

const toRegister = () => {
    router.push('/register')
}

const getCaptcha = () => {
    axios.get('/api/user/getCaptcha').then(res => {
        captchaImg.value = res.data.data
    })
}

onMounted(() => {
    getCaptcha()
})

onBeforeUnmount(() => {
    clearInterval(timer.value)
})

</script>
<style lang='scss' scoped>
.login{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background: url('../../assets/login/bg.jpeg') no-repeat;
  background-size:  100% 100%;
  .container{
    width: 400px;
    height: 320px;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .check_pic{
      width: 100px;
      height: 32px;
    }
    .btns{
      width: 180px;
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .login_type{
      position: absolute;
      left: 30px;
      bottom: 20px;
      color: #337ecc;
    }
    .register_link{
      position: absolute;
      right: 30px;
      bottom: 20px;
      color: #337ecc;
    }
  }
}
</style>